package com.yuanyi.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import static com.yuanyi.util.AccessTokenUtil.APPID;
import static com.yuanyi.util.AccessTokenUtil.APPSECRET;

@Component
public class FindAccessTokenTask {

    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Scheduled(fixedRate = 1000*60*60*2)
    public void find() throws Exception {
        String accessToken = (String) redisTemplate.opsForValue().get("access_token");
        if(accessToken==null) {
            AccessTokenUtil.findAccessToken(redisTemplate);
        }

        
    }

    public static void main(String[] args) throws Exception {
        URL url = new URL("https://api.weixin.qq.com/cgi-bin/token?" +
                "grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        BufferedReader br = new BufferedReader(
                new InputStreamReader(con.getInputStream(),"utf-8")
        );

        String str;
        StringBuffer sb = new StringBuffer();
        while((str=br.readLine())!=null){
            System.out.println(str);
            sb.append(str);
        }

        JSONObject obj =  JSON.parseObject(sb.toString());
       System.out.println( obj.getString("access_token"));;
    }
}
